package org.liveboardgames.agricola.control.delegates
{
	import com.adobe.cairngorm.business.ServiceLocator;

	import mx.rpc.IResponder;

	import org.liveboardgames.agricola.control.delegates.helper.GameHelper;
	import org.liveboardgames.agricola.model.AgricolaModelLocator;
	import org.liveboardgames.agricola.vo.player.Player;
	import org.liveboardgames.common.dictionary.collections.HashCollection;
	import org.liveboardgames.common.dictionary.collections.IMap;

	public class BuildRoomDelegate
	{
		private var _responder:IResponder;

		private var _service:Object;

		public function BuildRoomDelegate(responder:IResponder)
		{
			this._service = ServiceLocator.getInstance().getRemoteObject("farmService");
			this._responder = responder;
		}

		public function buildRoom(player:Player, cost:IMap, numberOfRooms:int):void
		{
//			setTimeout(buildRoomService, 0, player, cost, numberOfRooms);
			// TODO: for now, this service only deals with the payment of the room. 
			// To handle undos, it should deal with payment and construction at the same time.
			var call:Object = _service.buildRoom(AgricolaModelLocator.getInstance().game.id, player.farm.id, numberOfRooms,
				cost.toObject());
			call.resultHandler = _responder.result;
			call.faultHandler = _responder.fault;
		}

		private function buildRoomService(player:Player, cost:IMap, numberOfRooms:int):void
		{
			// Compute the total cost
			var totalCost:IMap = new HashCollection();

			for each (var resource:String in cost.getKeys())
			{
				var quantity:int = cost.getValue(resource);
				totalCost.put(resource, numberOfRooms * quantity);
			}

			GameHelper.pay(player.farm, totalCost);
		}
	}
}